package com.cluster.user.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.cluster.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.cluster.user.dao.UserDao;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service   //  交由spring容齐管理
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;


    @Override
    public String updateUser(User user) {
        log.info("updateUser body={}", JSONUtil.parse(user).toString());
        user.setPassword(md5Encrypt(user.getPassword()));
        if (!redisTemplate.hasKey("PHONE:" + user.getPhone())) {
            return "验证码过期";
        } else {
            String string = redisTemplate.opsForValue().get("PHONE:" + user.getPhone()).toString();
            if (!string.equals(user.getCode())) {
                return "验证码错误";
            }

            int i = 0;
            try {
                i = userDao.updateUser(user);
            } catch (Exception e) {
                log.error("updateUser fail");
                throw new RuntimeException(e);
            }
            if (i > 0) {
                return "success";
            } else {
                return "用户不存在";
            }
        }

    }

    @Override
    public String addUser(User user) {
        user.setStatus("1");
        log.info("addUser body={}", JSONUtil.parse(user).toString());
        user.setPassword(md5Encrypt(user.getPassword()));
        if (!redisTemplate.hasKey("PHONE:" + user.getPhone())) {
            return "验证码过期";
        } else {
            String string = redisTemplate.opsForValue().get("PHONE:" + user.getPhone()).toString();
            if (!string.equals(user.getCode())) {
                return "验证码错误";
            }
            User result = null;
            try {
                result = userDao.queryUserByPhone(user.getPhone(), user.getServerCode());
            } catch (Exception e) {
                log.error("查询失败");
                throw new RuntimeException(e);
            }
            if (Optional.ofNullable(result).isPresent()) {
                return "用户已存在";
            }
            return userDao.addUser(user) > 0 ? "success" : "fail";
        }
    }

    //密码错误
    //
    //验证码过期
    @Override
    public String login(User user) {
        log.info("login body={}", JSONUtil.parse(user).toString());
        User result = null;
        try {
            result = userDao.queryUserByPhone(user.getPhone(), user.getServerCode());
        } catch (Exception e) {
            log.error("查询失败");
            throw new RuntimeException(e);
        }
        String encode = md5Encrypt(user.getPassword());
        if (!Optional.ofNullable(result).isPresent()) {
            return "手机号未注册";
        } else if (!StrUtil.equals(encode, result.getPassword())) {
            return "密码错误";
        } else {
            return "success";
        }
    }

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public String sendMessage(User user) {
        log.info("sendMessage body={}", JSONUtil.parse(user).toString());
        String code = user.getCode();
        if (StrUtil.isBlank(code)) {
            code = randomCode();
        }
        try {
            LocalDateTime currentTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedTime = currentTime.format(formatter);

            String webhookUrl = "http://121.43.172.190:7862/smsv2";
            String message = "";
            // 构建消息内容
            if (StrUtil.equals("002", user.getServerCode())) {
                message = JSONUtil.createObj()
                        .set("action", "p2p")
                        .set("account", "707437")
                        .set("password", "zJmAv7aWrKRP2")
                        .set("extno", "106901956")
                        .set("atTime", formattedTime)
                        .set("mobileContentKvp", JSONUtil.createObj().set(user.getPhone(), "【会飞的日历】您的验证码是:" + code + "，请输入以完成验证。如非本人操作，请忽略本短信。"))
                        .toString();
            } else if (StrUtil.equals("003", user.getServerCode())) {
                message = JSONUtil.createObj()
                        .set("action", "p2p")
                        .set("account", "707437")
                        .set("password", "zJmAv7aWrKRP2")
                        .set("extno", "106901956")
                        .set("atTime", formattedTime)
                        .set("mobileContentKvp", JSONUtil.createObj().set(user.getPhone(), "【壁纸小镇】您的验证码是:" + code + "，请输入以完成验证。如非本人操作，请忽略本短信。"))
                        .toString();
            } else {
                message = JSONUtil.createObj()
                        .set("action", "p2p")
                        .set("account", "707437")
                        .set("password", "zJmAv7aWrKRP2")
                        .set("extno", "106901956")
                        .set("atTime", formattedTime)
                        .set("mobileContentKvp", JSONUtil.createObj().set(user.getPhone(), "【克拉斯特记账】您的验证码是:" + code + "，请输入以完成验证。如非本人操作，请忽略本短信。"))
                        .toString();
            }


            // 发送 POST 请求
            String response = HttpUtil.post(webhookUrl, message);
            // 打印响应
            log.info("sendMessage sucess body={}", response);
            redisTemplate.opsForValue().set("PHONE:" + user.getPhone(), code, 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("发送短信失败,响应信息");
            throw new RuntimeException(e);
        }
        return "success";
    }

    private String randomCode() {
        Random random = new Random();
        // 生成一个 6 位数的验证码
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int digit = random.nextInt(10); // 生成 0 到 9 的随机数字
            code.append(digit);
        }
        return code.toString();
    }

    public String md5Encrypt(String input) {
        try {
            // 创建 MD5 实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算哈希值
            byte[] messageDigest = md.digest(input.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String setRedisKey(String phone) {
        redisTemplate.opsForValue().set("PHONE:" + phone, 123456, 60, TimeUnit.SECONDS);
        return "ok";
    }


    @Override
    public String cancelAccount(User user) {
        log.info("cancelAccount body={}", JSONUtil.parse(user).toString());
        User result = null;
        try {
            result = userDao.queryUserByPhone(user.getPhone(), user.getServerCode());
        } catch (Exception e) {
            log.error("查询失败");
            throw new RuntimeException(e);
        }
        String encode = md5Encrypt(user.getPassword());
        if (!Optional.ofNullable(result).isPresent()) {
            return "手机号未注册";
        } else if (!StrUtil.equals(encode, result.getPassword())) {
            return "密码错误";
        } else {
            userDao.cancelAccount(user);
            return "success";
        }
    }


}
